<?php
/**
* 购物车模块Api Service
*
* 购物车模块Api Service的注意及说明
* 以下use模块请不要互相伤害
*
* @author    xiecz <xiecz@yunys.com.cn>
* @copyright 2016 QuanZhouYunYiShang Inc.
*/
namespace App\Services\Car;

use Log;

use App\Services\Tool\DataBase\SQL;
use App\Services\Tool\GeneralTool;
use App\Services\Tool\Car\CarTool;
use App\Services\Coupons\CouponsService;

class Api{

    function __construct(CouponsService $couponService,
                         CarTool $carTool){
        $this->couponService   = $couponService;
        $this->carTool  = $carTool;
    }

    /**
        添加购物车√
        参数：
            user_id         用户编号
            product_id      商品编号
            colour_name     颜色
            size_name       尺码
            quantity        数量
     */
    function addShopCar($input,$type = 1){
        try{
            //判断参数是否足够
            if(!isset($input['user_id'])||!isset($input['product_id'])||!isset($input['size_name'])||!isset($input['colour_name'])){
                return GeneralTool::createResult('','M00002');
            }
            //判断用户是否存在
            if(!$this->carTool->isUser($input['user_id'])) return GeneralTool::createResult('','M05001');

            if(empty($input['quantity'])||!is_numeric($input['quantity'])||$input['quantity']<=0){
                $input['quantity']  = 1;
            }else if($input['quantity']>=99){
                $input['quantity']  = 99;
            }else{
                $input['quantity']  = ceil($input['quantity']);
            }

            //判断商品 尺码 颜色 库存是否符合
            $can_buy = $this->carTool->can_order($input['product_id'], $input['colour_name'], $input['size_name'], $input['quantity'], $input['user_id']);
            if(!isset($can_buy['state']) || ($can_buy['state'] != 'M00000' && $can_buy['state'] != 'M08025')) return $can_buy;

            $product_temp_id = $this->carTool->getTemplateByProductId($input['product_id']);
            if(!$product_temp_id) return GeneralTool::createResult('','M08001');

            $brand_id = $this->carTool->getBrandIdByProductTempId($product_temp_id);
            if(!$brand_id) return GeneralTool::createResult('','M08002');

            //判断是否已添加
            $arr    = array('user_id'=>$input['user_id'],
                            'product_id'=>$input['product_id'],
                            'size_name'=>$input['size_name'],
                            'colour_name'=>$input['colour_name'],
                            'product_temp_id'=>$product_temp_id,
                            'brand_id'=>$brand_id,
                            'state'=>1);

            $car    = SQL::first(array('table'=>'shop_cars',
                                       'where'=>$arr));

            if(isset($car)){
                //dd($input);
               $new_quantity = $car->quantity + $input['quantity'] > 99 ? 99 : $car->quantity + $input['quantity'];

               $can_buy = $this->carTool->can_order($input['product_id'],
                                                     $input['colour_name'],
                                                     $input['size_name'],
                                                     $new_quantity,
                                                     $input['user_id']);
               if(!isset($can_buy['state'])||($can_buy['state'] != 'M00000' && $can_buy['state'] != 'M08025')) return $can_buy;
               //添加数量
               $result = SQL::update(array('table'=>'shop_cars',
                                           'where'=>$arr,
                                           'update'=>['quantity'=>$new_quantity,
                                                       'updated_at'=>time()]));

                $quantitys = $this->carTool->get_shop_car_quantity($input,2);
                $ar['good_total_quantity']  = $quantitys['good_total_quantity'];      //商品总数
                $ar['good_settlement_quantity'] = $quantitys['good_settlement_quantity']; //可结算商品总数

                return $result?GeneralTool::createResult($ar,'M00000'):
                               GeneralTool::createResult('','M00001');
            }else{
                //添加数据
                $arr['is_select']   = isset($input['is_select'])? $input['is_select'] : 1;
                $arr['quantity']    = $input['quantity'];
                $arr['created_at']  = time();
                $arr['updated_at']  = $arr['created_at'];
                $result = SQL::insert(array('table'=>'shop_cars',
                                            'insert'=>$arr));

                $quantitys = $this->carTool->get_shop_car_quantity($input,2);
                $ar['good_total_quantity']  = $quantitys['good_total_quantity'];      //商品总数
                $ar['good_settlement_quantity'] = $quantitys['good_settlement_quantity']; //可结算商品总数

                return $result?GeneralTool::createResult($ar,'M00000'):
                               GeneralTool::createResult('','M00001');
            }
        }catch(\Exception $e){
            Log::info($e);
            SQL::CatchDo();
            return GeneralTool::createResult('','M00003');
        }finally{
            if($type == 1) SQL::FinallyDo();
        }
    }

    /**
        选择或取消选中√
        参数:
            user_id         用户编号
            shop_car_id     购物车编号

     */
    function carSelect($input){
        try{
            //判断参数是否足够
            if(!isset($input['user_id'])){
                return GeneralTool::createResult('','M00002');
            }

            //判断用户是否存在
            if(!$this->carTool->isUser($input['user_id'])) return GeneralTool::createResult('','M05001');

            //
            $arr['user_id']     = $input['user_id'];
            $arr['shop_car_id'] = $input['shop_car_id'];
            $arr['state']       = 1;
            $is_select  = SQL::pluck(array('table'=>'shop_cars',
                                           'where'=>$arr,
                                           'pluck'=>'is_select'));
            if(!isset($is_select)){
                return GeneralTool::createResult('','M05005');
            }
            $result = 0;
            $ar['is_select']    = 0;
            if($is_select==0){
                $ar['is_select']    = 1;
                $result = SQL::update(array('table'=>'shop_cars',
                                            'where'=>$arr,
                                            'update'=>array('is_select'=>1,
                                                            'updated_at'=>time())));
            }else{

                $result = SQL::update(array('table'=>'shop_cars',
                                            'where'=>$arr,
                                            'update'=>array('is_select'=>0,
                                                            'updated_at'=>time())));
            }

            if($result==0){
                return GeneralTool::createResult('','M00001');
            }

            //获取购物车商品价格
            $ar['total_fee']    = $this->carTool->get_shop_car_total_fee(array('user_id'=>$input['user_id']));

            $quantitys = $this->carTool->get_shop_car_quantity($input);

            $ar['good_total_quantity']      = $quantitys['good_total_quantity'];      //商品总数
            $ar['good_settlement_quantity'] = $quantitys['good_settlement_quantity']; //可结算商品总数
            $ar['is_all_select']            = $quantitys['is_all_select'];            //是否全选

            return GeneralTool::createResult($ar,'M00000');
        }catch(\Exception $e){
            Log::info($e);
            SQL::CatchDo();
            return GeneralTool::createResult('','M00003');
        }finally{
            SQL::FinallyDo();
        }
    }

    /**
        清除无效商品√
        参数：
            user_id         用户编号
     */
    function shopCarCleanFromInvalid($input){
        try{
            //判断参数是否足够
            if(!isset($input['user_id'])){
                return GeneralTool::createResult('','M00002');
            }

            //判断用户是否存在
            if(!$this->carTool->isUser($input['user_id'])) return GeneralTool::createResult('','M05001');

            //获取无效商品的购物车编号
            $invalid_shop_car_id = $this->carTool->get_shop_car_id_invalid($input['user_id']);

            //清除
            $result = $this->carTool->clean_invaild($invalid_shop_car_id);

            //获取购物车商品价格
            $ar['total_fee']    = $this->carTool->get_shop_car_total_fee(array('user_id'=>$input['user_id']));

            $quantitys = $this->carTool->get_shop_car_quantity($input);

            $ar['good_total_quantity']      = $quantitys['good_total_quantity'];      //商品总数
            $ar['good_settlement_quantity'] = $quantitys['good_settlement_quantity']; //可结算商品总数
            $ar['is_all_select']            = $quantitys['is_all_select'];            //是否全选

            return GeneralTool::createResult($ar,'M00000');

        }catch(\Exception $e){
            Log::info($e);
            SQL::CatchDo();
            return GeneralTool::createResult('','M00003');
        }finally{
            SQL::FinallyDo();
        }
    }

    /**
        购物车全选或全取消√
        参数：
            user_id         用户编号
            is_all_select   当前全选状态 1当前全选0未全选
     */
    function shopCarCheckAllOrCancelAll($input){
        try{
            //判断参数是否足够
            if(!isset($input['user_id'])||!isset($input['is_all_select'])){
                return GeneralTool::createResult('','M00002');
            }

            //判断用户是否存在
            if(!$this->carTool->isUser($input['user_id'])) return GeneralTool::createResult('','M05001');

            $arr['is_select'] = $input['is_all_select']?0:1;

            $result = SQL::update(array('table'=>'shop_cars',
                                        'where'=>array('user_id'=>$input['user_id'],
                                                       'state'=>1),
                                        'update'=>$arr));

            //获取购物车商品价格
            $ar['total_fee']    = $this->carTool->get_shop_car_total_fee(array('user_id'=>$input['user_id']));

            $quantitys = $this->carTool->get_shop_car_quantity($input);

            $ar['good_total_quantity']      = $quantitys['good_total_quantity'];      //商品总数
            $ar['good_settlement_quantity'] = $quantitys['good_settlement_quantity']; //可结算商品总数
            $ar['is_all_select']            = $quantitys['is_all_select'];            //是否全选

            return GeneralTool::createResult($ar,'M00000');

        }catch(\Exception $e){
            Log::info($e);
            SQL::CatchDo();
            return GeneralTool::createResult('','M00003');
        }finally{
            SQL::FinallyDo();
        }
    }

    /**
        购物车编辑√
        参数：
            user_id             用户编号
            body                购物车内容
            [
              {
                product_id          作品编号
                size_name           尺码
                is_select           选中
                colour_name         颜色编号
                quantity            数量
              }
            ]
     */
    function editCarComplete($input){

        try{
            //判断参数是否足够
            if(!isset($input['user_id'])||!isset($input['body'])){
                return GeneralTool::createResult('','M00002');
            }

            //判断用户是否存在
            if(!$this->carTool->isUser($input['user_id'])) return GeneralTool::createResult('','M05001');

            //清空购物车
            $result = $this->carTool->shop_car_clean(['user_id'=>$input['user_id'],'state'=>1]);

            $body = json_decode($input['body']);

            try{
                Log::info($input['body']);
            }catch(\Exception $e){
                SQL::insert(['table'=>'active_logs',
                             'insert'=>['message'=>$input['body'],
                                        'time'=>time()]]);
            }
            if(!isset($body) || !is_array($body)) return GeneralTool::createResult('','M00001');

            foreach($body as $bo){

                if(!isset($bo->product_id)){
                    $str[]  = '产品编号不存在';
                    continue;
                }else if(!isset($bo->size_name)){
                    $str[]  = '产品尺码不存在';
                    continue;
                }else if(!isset($bo->colour_name)){
                    $str[]  = '产品颜色不存在';
                    continue;
                }else if(!isset($bo->quantity)){
                    $str[]  = '产品数量不存在';
                    continue;
                }

                $result = $this->addShopCar(['user_id'     =>$input['user_id'],
                                             'product_id'  => $bo->product_id,
                                             'size_name'   => $bo->size_name,
                                             'colour_name' => $bo->colour_name,
                                             'quantity'    => $bo->quantity,
                                             'is_select'   => (isset($bo->is_select) && $bo->is_select ? 1 : 0 )],
                                             2);
                if($result['state'] != 'M00000'){
                    $state = $result['state'];
                    SQL::CatchDo();
                    return ['state'=>'M00001','result'=>((object)array()),'message'=>$bo->product_id.$result['message']];
                }
            }

            //获取购物车商品价格
            $ar['total_fee']    = $this->carTool->get_shop_car_total_fee(array('user_id'=>$input['user_id']));

            $quantitys = $this->carTool->get_shop_car_quantity($input);

            $ar['good_total_quantity']      = $quantitys['good_total_quantity'];      //商品总数
            $ar['good_settlement_quantity'] = $quantitys['good_settlement_quantity']; //可结算商品总数
            $ar['is_all_select']            = $quantitys['is_all_select'];            //是否全选

            return ['state' => 'M00000', 'result' => $ar, 'message'=>'编辑成功'];

        }catch(\Exception $e){
            try{
                Log::info($e);
            }catch(\Exception $e){
                SQL::insert(['table'=>'active_logs',
                             'insert'=>['message'=>$e,
                                        'time'=>time()]]);
            }
            SQL::CatchDo();
            return GeneralTool::createResult('','M00003');
        }finally{
            SQL::FinallyDo();
        }
    }

    /**
        购物车列表√
        参数：
            user_id         用户编号
     */
    function shopCarList($input){
        try{
            //判断参数是否存在
            if(!isset($input['user_id'])){
                return GeneralTool::createResult('','M00002');
            }

            //判断用户是否存在
            if(!$this->carTool->isUser($input['user_id'])) return GeneralTool::createResult('','M05001');

            $input['where'] = array('user_id'=>$input['user_id'],'state'=>1);
            $result = $this->carTool->getShopCarList($input);
            //dd($result);
            return GeneralTool::createResult($result,'M00000');
        }catch(\Exception $e){
            Log::info($e);
            SQL::CatchDo();
            return GeneralTool::createResult('','M00003');
        }finally{
            SQL::FinallyDo();
        }
    }

    /**
        购物车结算页
        参数：
            user_id         用户编号
     */
    function shopCarSubmit($input){
       try{
           //判断参数是否存在
           if(!isset($input['user_id'])){
               return GeneralTool::createResult('','M00002');
           }

           //判断用户是否存在
           if(!$this->carTool->isUser($input['user_id'])) return GeneralTool::createResult('','M05001');

           //购物车内容
           $input['where'] = array('user_id'=>$input['user_id'],'state'=>1,'is_select'=>1);
           $result         = $this->carTool->getShopCarList($input);

           //默认收货地址
           $receiving           = $this->carTool->defaultAddress($input['user_id']);
           $result['receiving'] = isset($receiving)?$receiving:((object)array());

           $coupons = $this->couponService->shopCarCoupons(['user_id'=>$input['user_id'],
                                                            'page'=>1,
                                                            'per_page'=>1]);
           if(isset($result['goods']['unvaild'])) $result['goods']['unvaild'] = [];
           $result['coupons']  = isset($coupons['state']) &&
                                 $coupons['state'] == 'M00000' &&
                                 isset($coupons['result']['data'][0]) ?
                                 $coupons['result']['data'][0] : (object)array();
           $result['total_price'] = $result['total_fee'];
           $result['total_fee'] = isset($result['coupons']) && isset($result['coupons']->total_fee) ?
                                  $result['coupons']->total_fee : $result['total_fee'] + $this->carTool->get_shop_car_postage($input);
           $result['total_fee'] = GeneralTool::priceFormat($result['total_fee']).'';
           return GeneralTool::createResult($result,'M00000');
       }catch(\Exception $e){
           Log::info($e);
           SQL::CatchDo();
           return GeneralTool::createResult('','M00003');
       }finally{
           SQL::FinallyDo();
       }
    }

    /**
        立即购买购物车结算页
        参数：
            user_id         用户编号
            product_id      作品编号
            colour_name     颜色编号
            size_name       尺码
            quantity        数量
     */
    function buyImmediatelySubmit($input){
       //判断参数是否足够
       if(!isset($input['user_id'])||!isset($input['product_id'])||!isset($input['colour_name'])||!isset($input['size_name']))
           return GeneralTool::createResult('','M00002');

       //判断用户是否存在
       if(!$this->carTool->isUser($input['user_id'])) return GeneralTool::createResult('','M05001');

       $input['product_temp_id'] = $this->carTool->getTemplateByProductId($input['product_id']);

       if(!isset($input['product_temp_id'])) return GeneralTool::createResult('','M08012');

       if(empty($input['quantity'])||!is_numeric($input['quantity'])||$input['quantity']<=0)
           $input['quantity']    = 1;
       else if($input['quantity']>=99)
           $input['quantity']    = 99;
       else
           $input['quantity']    = ceil($input['quantity']);

       $can_buy = $this->carTool->can_order($input['product_id'], $input['colour_name'], $input['size_name'], $input['quantity'], $input['user_id']);
       ///dd($can_buy);

       if($can_buy['state'] != 'M00000' && $can_buy['state'] != 'M08025') return $can_buy;

       //获取立即购买结算页数据
       $result = $this->carTool->buy_immediately_submit_goods($input);
       if(isset($result['goods']['unvaild'])) $result['goods']['unvaild'] = [];
       //默认收货地址
       $receiving           = $this->carTool->defaultAddress($input['user_id']);
       $result['receiving'] = isset($receiving)?$receiving:((object)array());

       $coupons = $this->couponService->buyImmediatelyCoupons(['user_id'         => $input['user_id'],
                                                               'page'            => 1,
                                                               'per_page'        => 1,
                                                               'product_id'      => $input['product_id'],
                                                               'colour_name'     => $input['colour_name'],
                                                               'size_name'       => $input['size_name'],
                                                               'quantity'        => $input['quantity']]);

       $result['total_fee'] += $this->carTool->get_postage_by_product_temp_id($input['product_temp_id']);
       $result['coupons']    = isset($coupons['state']) &&
                                $coupons['state'] == 'M00000' &&
                                isset($coupons['result']['data'][0]) ?
                                $coupons['result']['data'][0] : (object)array();

       $result['total_fee']   = isset($result['coupons']) && isset($result['coupons']->total_fee) ? $result['coupons']->total_fee : $result['total_fee'];
       $result['total_fee']   = GeneralTool::priceFormat($result['total_fee']) . '';
        return GeneralTool::createResult($result,'M00000');
    }


    /**
        批量删除购物车商品
        参数：
            user_id         用户编号
            body            购物车编号json
     */
    function delete_shop_car($input){
        try{
             //判断参数是否足够
            if(!isset($input['user_id'])||!isset($input['body']))
                return GeneralTool::createResult('','M00002');

            //判断用户是否存在
            if(!$this->carTool->isUser($input['user_id'])) return GeneralTool::createResult('','M05001');

            $shop_car_id = json_decode($input['body']);
            if(!isset($shop_car_id) || !is_array($shop_car_id)) return GeneralTool::createResult('','M00001');

            $result      = $this->carTool->delete_shop_car_by_id($input, $shop_car_id);

            if($result != 'M00000') return GeneralTool::createResult('', $result);

            //获取购物车商品价格
            $ar['total_fee']    = $this->carTool->get_shop_car_total_fee(array('user_id'=>$input['user_id']));

            $quantitys = $this->carTool->get_shop_car_quantity($input);

            $ar['good_total_quantity']      = $quantitys['good_total_quantity'];      //商品总数
            $ar['good_settlement_quantity'] = $quantitys['good_settlement_quantity']; //可结算商品总数
            $ar['is_all_select']            = $quantitys['is_all_select'];            //是否全选

            return $result?['state' => 'M00000', 'result' => $ar, 'message' => '删除成功']:
                           GeneralTool::createResult('','M00001');

        }catch(\Exception $e){
            Log::info($e);
            SQL::CatchDo();
            return GeneralTool::createResult('','M00003');
        }finally{
            SQL::FinallyDo();
        }
    }

    /**
        修改购物车商品数量
        参数：
            car_id          购物车编号
            user_id         用户编号
            number          数量
     */
    function updShopCarCreate($input){
        try{
            //判断参数是否足够
            if(!isset($input['shop_car_id'])||!isset($input['user_id'])||!isset($input['number']))
                return GeneralTool::createResult('','M00002');

            //判断用户是否存在
            if(SQL::count(array('table'=>'users','where'=>array('user_id'=>$input['user_id'],'state'=>1)))!=1)
                return GeneralTool::createResult('','M05001');

            //判断购物车中是否存在该商品
            if(SQL::count(array('table'=>'shop_cars',
                                'where'=>array('shop_car_id'=>$input['shop_car_id'],
                                               'user_id'=>$input['user_id'],
                                               'state'=>1)))!=1)
                return GeneralTool::createResult('','M05005');

            if(empty($input['number'])||!is_numeric($input['number'])||$input['number']<=0)
                $input['number']    = 1;
            else if($input['number']>=99)
                $input['number']   = 99;
            else
                $input['number']    = ceil($input['number']);

            $result = SQL::update(array('table'=>'shop_cars',
                                        'where'=>array('shop_car_id'=>$input['shop_car_id'],
                                                       'user_id'=>$input['user_id'],
                                                       'state'=>1),
                                        'update'=>array('num'=>$input['number'])));

            //获取购物车商品价格
            $ar['total_fee']    = OrderTool::getShopCarTotalFee(array('user_id'=>$input['user_id']));
            $ar['number']       = $input['number'];
            $ar['good_num']     = OrderTool::getShopCarSelectNum(array('user_id'=>$input['user_id']));

            return GeneralTool::createResult($ar,'M00000');


        }catch(\Exception $e){
            Log::info($e);
            SQL::CatchDo();
            return GeneralTool::createResult('','M00003');
        }finally{
            SQL::FinallyDo();
        }
    }

    /**
        工具
     */

    function test($input){
        $result = JpushTool::push_phone('测试',0,'2016081209575551555356');
        dd($result);
        return $result;
    }

}
